package com.qq.servlet;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.qq.bean.Dynamics;
import com.qq.bean.Friend;
import com.qq.bean.FriendshipVO;
import com.qq.service.DynamicsService;
import com.qq.service.FriendshipService;
import com.qq.service.UsersService;
import com.qq.service.impl.DynamicsServiceImpl;
import com.qq.service.impl.FriendshipServiceImpl;
import com.qq.service.impl.UsersServiceImpl;


@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
	

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UsersService us = new UsersServiceImpl();
		FriendshipService fs = new FriendshipServiceImpl();
		//System.out.println("123");
		request.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		//保存账号密码
		String autoSave = request.getParameter("autoSave");
		if("on".equals(autoSave)){
			Cookie cookie = new Cookie("account",account);
			Cookie cookie2 = new Cookie("upwd",password);
			cookie.setMaxAge(60*60*24*7);
			cookie2.setMaxAge(60*60*24*7);
			response.addCookie(cookie);
			response.addCookie(cookie2);
		}else{
			Cookie cookie = new Cookie("account","");
			Cookie cookie2 = new Cookie("upwd","");
			cookie.setMaxAge(0);
			cookie2.setMaxAge(0);
			response.addCookie(cookie);
			response.addCookie(cookie2);
		}
		List<FriendshipVO> myFriends = us.selectMyFriend(account);
		Map<String,Object> map = us.usersLogin(account, password);
		List<FriendshipVO> addFriend = fs.selectWhoaddMe(account);
		DynamicsService dy = new DynamicsServiceImpl();
		List<Dynamics> dynamicsAll = dy.selectMyfriendAllDynamics(account);
		
		//List<Chatrecords> allmsg = us.selectMessageForMyfriend(account, friend_accounts);
		if(map.get("loginUser")!=null){
			System.out.println(map.get("loginUser").toString());
			session.setAttribute("loginUser", map.get("loginUser"));
			session.setAttribute("dynamicsAll", dynamicsAll);
			session.setAttribute("myFriends", myFriends);
			System.out.println(myFriends);
			session.setAttribute("addFriend", addFriend);
			response.sendRedirect("homepage.jsp");
		}else{
			request.setAttribute("msg",map.get("msg"));
			request.getRequestDispatcher("login.jsp").forward(request,response);
		}
		
	}

}
